<template>
  <el-drawer v-model="drawerVisible" title="布局设置" size="300px" :z-index="2000">
    <!-- 布局切换 -->
    <el-divider class="divider" content-position="center">
      <el-icon><Notification /></el-icon>
      布局切换
    </el-divider>
    <div class="layout-box mb30">
      <el-tooltip effect="dark" content="纵向" placement="top" :show-after="200">
        <div :class="['layout-item layout-vertical', { 'is-active': layout == 'vertical' }]" @click="() => setLayout('vertical')">
          <div class="layout-dark"></div>
          <div class="layout-container">
            <div class="layout-light"></div>
            <div class="layout-content"></div>
          </div>
          <el-icon v-if="layout == 'vertical'"><CircleCheckFilled /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip effect="dark" content="经典" placement="top" :show-after="200">
        <div :class="['layout-item layout-classic', { 'is-active': layout == 'classic' }]" @click="() => setLayout('classic')">
          <div class="layout-dark"></div>
          <div class="layout-container">
            <div class="layout-light"></div>
            <div class="layout-content"></div>
          </div>
          <el-icon v-if="layout == 'classic'"><CircleCheckFilled /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip effect="dark" content="横向" placement="top" :show-after="200">
        <div :class="['layout-item layout-transverse', { 'is-active': layout == 'transverse' }]" @click="() => setLayout('transverse')">
          <div class="layout-dark"></div>
          <div class="layout-content"></div>
          <el-icon v-if="layout == 'transverse'"><CircleCheckFilled /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip effect="dark" content="分栏" placement="top" :show-after="200">
        <div :class="['layout-item layout-columns', { 'is-active': layout == 'columns' }]" @click="() => setLayout('columns')">
          <div class="layout-dark"></div>
          <div class="layout-light"></div>
          <div class="layout-content"></div>
          <el-icon v-if="layout == 'columns'"><CircleCheckFilled /></el-icon>
        </div>
      </el-tooltip>
    </div>

    <!-- 全局主题 -->
    <el-divider class="divider" content-position="center">
      <el-icon><ColdDrink /></el-icon>
      全局主题
    </el-divider>
    <div class="theme-section">
      <!-- 主题模式选择器 -->
      <div class="theme-item-full mb20">
        <span class="mb10">主题模式</span>
        <div class="theme-mode-box">
          <div 
            :class="['theme-mode-item', { 'is-active': themeMode === 'light' }]"
            @click="() => setThemeMode('light')"
          >
            <div class="mode-icon light-icon">
              <el-icon><Sunny /></el-icon>
            </div>
            <div class="mode-name">明亮</div>
            <el-icon v-if="themeMode === 'light'" class="check-icon"><CircleCheckFilled /></el-icon>
          </div>
          
          <div 
            :class="['theme-mode-item', { 'is-active': themeMode === 'dark' }]"
            @click="() => setThemeMode('dark')"
          >
            <div class="mode-icon dark-icon">
              <el-icon><Moon /></el-icon>
            </div>
            <div class="mode-name">暗黑</div>
            <el-icon v-if="themeMode === 'dark'" class="check-icon"><CircleCheckFilled /></el-icon>
          </div>
          
          <div 
            :class="['theme-mode-item', { 'is-active': themeMode === 'auto' }]"
            @click="() => setThemeMode('auto')"
          >
            <div class="mode-icon auto-icon">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="mode-name">跟随系统</div>
            <el-icon v-if="themeMode === 'auto'" class="check-icon"><CircleCheckFilled /></el-icon>
          </div>
        </div>
      </div>

      <div class="theme-item">
        <span>主题颜色</span>
        <el-color-picker 
          v-model="primary" 
          :predefine="colorList" 
          @change="changePrimaryColor"
          @update:modelValue="changePrimaryColor"
          @active-change="handleActiveColorChange"
        />
      </div>
      <div class="theme-item">
        <span>
          紧凑布局
          <el-tooltip content="减小组件间距和尺寸，适合显示更多内容" placement="top">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
        <el-switch v-model="isCompact" @change="changeLayoutDensity" />
      </div>
      <div class="theme-item mb40">
        <span>
          显示动画
          <el-tooltip content="控制页面过渡和元素动画效果" placement="top">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
        <el-switch v-model="showAnimation" @change="changeAnimationMode" />
      </div>
    </div>

    <!-- 界面设置 -->
    <el-divider class="divider" content-position="center">
      <el-icon><Setting /></el-icon>
      界面设置
    </el-divider>
    <div class="theme-item">
      <span>折叠菜单</span>
      <el-switch v-model="isCollapse" @change="setCollapse" />
    </div>
    <div class="theme-item">
      <span>面包屑</span>
      <el-switch v-model="breadcrumb" @change="setBreadcrumb" />
    </div>
    <div class="theme-item">
      <span>面包屑图标</span>
      <el-switch v-model="breadcrumbIcon" @change="setBreadcrumbIcon" />
    </div>
    <div class="theme-item">
      <span>标签栏</span>
      <el-switch v-model="tabs" @change="setTabs" />
    </div>
    <div class="theme-item">
      <span>标签栏图标</span>
      <el-switch v-model="tabsIcon" @change="setTabsIcon" />
    </div>
    <div class="theme-item">
      <span>是否显示水印</span>
      <el-switch v-model="isWatermark" @change="setWatermark" />
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useTheme } from "../../hooks/useTheme";
import { useGlobalStore } from "../../store/modules/global";
import { LayoutType } from "../../store/interface";
import mittBus from "../../utils/mittBus";
import { ColdDrink, Setting, Notification, CircleCheckFilled, QuestionFilled, Sunny, Moon, Monitor } from "@element-plus/icons-vue";
import actions from "../../stores/globalState";
import { PRESET_COLORS } from "../../config/theme";

const { changePrimary, setAsideTheme } = useTheme();

const globalStore = useGlobalStore();
const { layout, primary, isCollapse, breadcrumb, breadcrumbIcon, tabs, tabsIcon, isWatermark } =
  storeToRefs(globalStore);

// 新增的主题设置项
const isCompact = ref(false);
const showAnimation = ref(true);

// 主题模式
const themeMode = ref<'light' | 'dark' | 'auto'>('light');

// 预定义主题颜色（已包含行业主题颜色）
const colorList = [...PRESET_COLORS] as string[];

// 设置主题模式
const setThemeMode = (mode: 'light' | 'dark' | 'auto') => {
  console.log('[ThemeDrawer] 设置主题模式:', mode);
  themeMode.value = mode;
  
  if (mode === 'auto') {
    // 跟随系统
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    console.log('[ThemeDrawer] 跟随系统 - 系统主题为:', prefersDark ? '暗黑' : '明亮');
    globalStore.setGlobalState("isDark", prefersDark);
    // 侧边栏跟随系统主题
    globalStore.setGlobalState("asideInverted", prefersDark);
    
    // 监听系统主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleSystemThemeChange = (e: MediaQueryListEvent) => {
      if (themeMode.value === 'auto') {
        console.log('[ThemeDrawer] 系统主题变化:', e.matches ? '暗黑' : '明亮');
        globalStore.setGlobalState("isDark", e.matches);
        globalStore.setGlobalState("asideInverted", e.matches);
        switchDark();
      }
    };
    // 移除旧的监听器（避免重复）
    mediaQuery.removeEventListener('change', handleSystemThemeChange);
    // 添加新的监听器
    mediaQuery.addEventListener('change', handleSystemThemeChange);
  } else {
    const isDarkMode = mode === 'dark';
    console.log('[ThemeDrawer] 设置主题模式为:', mode, '暗黑状态:', isDarkMode);
    globalStore.setGlobalState("isDark", isDarkMode);
    // 明亮模式：侧边栏使用浅色（asideInverted = false）
    // 暗黑模式：侧边栏使用深色（asideInverted = true）
    globalStore.setGlobalState("asideInverted", isDarkMode);
  }
  
  // 保存主题模式
  localStorage.setItem('theme-mode', mode);
  
  // 应用主题（switchDark 内部已经会调用 setAsideTheme，不需要重复调用）
  console.log('[ThemeDrawer] 应用主题，当前状态:', {
    mode,
    isDark: globalStore.isDark,
    asideInverted: globalStore.asideInverted,
    layout: globalStore.layout,
  });
  switchDark();
};

// 设置布局方式
const setLayout = (val: LayoutType) => {
  console.log('ThemeDrawer: 设置布局为:', val);
  // 更新 Pinia store
  globalStore.setGlobalState("layout", val);
  // 更新 Qiankun 全局状态
  actions.setGlobalState({ layout: val });
  console.log('ThemeDrawer: 布局已更新到 Pinia 和 Qiankun 全局状态');
  setAsideTheme();
  
  // 切换布局后刷新页面，确保微应用正确显示
  setTimeout(() => {
    window.location.reload();
  }, 100);
};

// 打开主题设置
const drawerVisible = ref(false);
mittBus.on("openThemeDrawer", () => {
  console.log('ThemeDrawer: 接收到 openThemeDrawer 事件');
  drawerVisible.value = true;
  console.log('ThemeDrawer: 抽屉已打开');
});

// 处理颜色选择器的 active-change 事件（悬停预览）
const handleActiveColorChange = (_color: string | null) => {
  // active-change 只是预览，不实际改变主题
  // 这里不做任何处理，等待用户确认（change 事件）
};

// 改变主题色（change 事件，用户确认选择）
const changePrimaryColor = (color: string | null) => {
  if (!color) {
    console.log('[ThemeDrawer] changePrimaryColor 接收到空值，跳过');
    return;
  }
  
  console.log('[ThemeDrawer] changePrimaryColor 接收到颜色:', color);
  
  // 验证颜色格式，兼容3位和6位hex
  const colorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  if (!colorRegex.test(color)) {
    console.warn('[ThemeDrawer] 无效的颜色格式:', color);
    return;
  }
  
  // 规范化颜色格式（确保是6位hex）
  let normalizedColor = color;
  if (color.length === 4) {
    // #RGB -> #RRGGBB
    normalizedColor = '#' + color.slice(1).split('').map(c => c + c).join('');
  }
  
  console.log('[ThemeDrawer] 规范化后的颜色:', normalizedColor);
  
  try {
    // 如果是"跟随系统"模式，先确保侧边栏状态正确（在changePrimary之前）
    if (themeMode.value === 'auto') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      console.log('[ThemeDrawer] 跟随系统模式 - 系统主题:', prefersDark ? '暗黑' : '明亮');
      // 确保侧边栏状态与系统主题一致
      globalStore.setGlobalState("asideInverted", prefersDark);
      globalStore.setGlobalState("isDark", prefersDark);
    }
    
    // 更新主题色（changePrimary 内部会调用 setAsideTheme）
    changePrimary(normalizedColor);
    
    // 同步到全局状态
    actions.setGlobalState({ primaryColor: normalizedColor });
    
    console.log('[ThemeDrawer] ✅ 主题颜色已更新:', normalizedColor);
  } catch (error) {
    console.error('[ThemeDrawer] ❌ 更新主题颜色失败:', error);
  }
};

// 改变布局密度（紧凑模式）
const changeLayoutDensity = (value: boolean) => {
  console.log('[ThemeDrawer] 切换紧凑布局:', value);
  const root = document.documentElement;
  
  if (value) {
    // 紧凑模式：减小间距和尺寸
    root.style.setProperty('--el-component-size', '28px');
    root.style.setProperty('--el-component-size-small', '20px');
    root.classList.add('compact-mode');
  } else {
    // 正常模式
    root.style.setProperty('--el-component-size', '32px');
    root.style.setProperty('--el-component-size-small', '24px');
    root.classList.remove('compact-mode');
  }
  
  // 保存到 localStorage
  localStorage.setItem('layout-compact', value.toString());
};

// 改变动画模式
const changeAnimationMode = (value: boolean) => {
  console.log('[ThemeDrawer] 切换动画效果:', value);
  const root = document.documentElement;
  
  if (value) {
    root.classList.remove('no-animation');
  } else {
    root.classList.add('no-animation');
  }
  
  // 保存到 localStorage
  localStorage.setItem('show-animation', value.toString());
};

// 设置折叠菜单
const setCollapse = () => {
  globalStore.setGlobalState("isCollapse", isCollapse.value);
  actions.setGlobalState({ isCollapse: isCollapse.value });
};

// 设置面包屑
const setBreadcrumb = () => {
  globalStore.setGlobalState("breadcrumb", breadcrumb.value);
  actions.setGlobalState({ breadcrumb: breadcrumb.value });
};

// 设置面包屑图标
const setBreadcrumbIcon = () => {
  globalStore.setGlobalState("breadcrumbIcon", breadcrumbIcon.value);
  actions.setGlobalState({ breadcrumbIcon: breadcrumbIcon.value });
};

// 设置标签页
const setTabs = () => {
  globalStore.setGlobalState("tabs", tabs.value);
  actions.setGlobalState({ tabs: tabs.value });
};

// 设置标签页图标
const setTabsIcon = () => {
  globalStore.setGlobalState("tabsIcon", tabsIcon.value);
  actions.setGlobalState({ tabsIcon: tabsIcon.value });
};

// 设置水印
const setWatermark = () => {
  globalStore.setGlobalState("isWatermark", isWatermark.value);
  actions.setGlobalState({ isWatermark: isWatermark.value });
};

// 初始化时读取设置
onMounted(() => {
  // 读取主题模式
  const savedThemeMode = localStorage.getItem('theme-mode') as 'light' | 'dark' | 'auto' | null;
  if (savedThemeMode) {
    themeMode.value = savedThemeMode;
    // 确保侧边栏颜色与主题模式一致
    if (savedThemeMode === 'light') {
      globalStore.setGlobalState("asideInverted", false);
    } else if (savedThemeMode === 'dark') {
      globalStore.setGlobalState("asideInverted", true);
    } else if (savedThemeMode === 'auto') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      globalStore.setGlobalState("asideInverted", prefersDark);
    }
    setAsideTheme();
  } else {
    // 根据当前暗黑模式状态初始化
    themeMode.value = globalStore.isDark ? 'dark' : 'light';
    globalStore.setGlobalState("asideInverted", globalStore.isDark);
    setAsideTheme();
  }
  
  // 读取紧凑布局设置
  const savedCompact = localStorage.getItem('layout-compact');
  if (savedCompact !== null) {
    isCompact.value = savedCompact === 'true';
    changeLayoutDensity(isCompact.value);
  }
  
  // 读取动画设置
  const savedAnimation = localStorage.getItem('show-animation');
  if (savedAnimation !== null) {
    showAnimation.value = savedAnimation === 'true';
    changeAnimationMode(showAnimation.value);
  } else {
    // 默认开启动画
    showAnimation.value = true;
  }
});
</script>

<script lang="ts">
export default {
  name: 'ThemeDrawer'
};
</script>

<style scoped lang="scss">
.divider {
  margin-top: 15px;
  .el-icon {
    position: relative;
    top: 2px;
    right: 5px;
    font-size: 15px;
  }
}

.theme-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 14px 0;
  z-index: 1;
  
  // 修复颜色选择器的层级问题
  :deep(.el-color-picker) {
    position: relative;
    z-index: 10;
  }
  span {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: var(--el-text-color-regular);
    .el-icon {
      margin-left: 3px;
      font-size: 15px;
      color: var(--el-text-color-regular);
      cursor: pointer;
    }
  }
}

.theme-item-full {
  display: flex;
  flex-direction: column;
  margin: 14px 0;
  z-index: 1;
  
  > span {
    display: block;
    font-size: 14px;
    color: var(--el-text-color-regular);
    margin-bottom: 10px;
  }
}

.mb10 {
  margin-bottom: 10px;
}

.mb20 {
  margin-bottom: 20px;
}

// 主题模式选择器
.theme-mode-box {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  
  .theme-mode-item {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    min-width: 70px;
    padding: 12px 8px;
    cursor: pointer;
    border-radius: 8px;
    border: 2px solid var(--el-border-color-lighter);
    background-color: var(--el-bg-color);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    
    &:hover {
      border-color: var(--el-color-primary-light-5);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }
    
    &.is-active {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
      box-shadow: 0 2px 12px 0 rgba(24, 144, 255, 0.2);
    }
    
    .mode-icon {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      margin-bottom: 6px;
      transition: all 0.3s;
      
      .el-icon {
        font-size: 22px;
      }
      
      &.light-icon {
        background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);
        color: #d63031;
      }
      
      &.dark-icon {
        background: linear-gradient(135deg, #2d3436 0%, #000000 100%);
        color: #ffeaa7;
      }
      
      &.auto-icon {
        background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
        color: #ffffff;
      }
    }
    
    .mode-name {
      font-size: 12px;
      color: var(--el-text-color-regular);
      font-weight: 500;
      text-align: center;
    }
    
    .check-icon {
      position: absolute;
      top: 6px;
      right: 6px;
      color: var(--el-color-primary);
      font-size: 16px;
      animation: scaleIn 0.3s ease-out;
    }
  }
}

@keyframes scaleIn {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.layout-box {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 10px 0 0;
  .layout-item {
    position: relative;
    box-sizing: border-box;
    width: 98px;
    height: 68px;
    padding: 6px;
    margin-bottom: 20px;
    cursor: pointer;
    border-radius: 5px;
    box-shadow: 0 0 5px 1px var(--el-border-color-lighter);
    transition: all 0.2s;
    .layout-dark {
      background-color: var(--el-color-primary);
      border-radius: 3px;
    }
    .layout-light {
      background-color: var(--el-color-primary-light-5);
      border-radius: 3px;
    }
    .layout-content {
      background-color: var(--el-color-primary-light-8);
      border: 1px dashed var(--el-color-primary);
      border-radius: 3px;
    }
    .el-icon {
      position: absolute;
      right: 10px;
      bottom: 10px;
      color: var(--el-color-primary);
      transition: all 0.2s;
    }
    &:hover {
      box-shadow: 0 0 5px 1px var(--el-border-color-darker);
    }
  }
  .is-active {
    box-shadow: 0 0 0 2px var(--el-color-primary) !important;
  }
  .layout-vertical {
    display: flex;
    justify-content: space-between;
    .layout-dark {
      width: 20%;
    }
    .layout-container {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 72%;
      .layout-light {
        height: 20%;
      }
      .layout-content {
        height: 67%;
      }
    }
  }
  .layout-classic {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .layout-dark {
      height: 20%;
    }
    .layout-container {
      display: flex;
      justify-content: space-between;
      height: 67%;
      .layout-light {
        width: 20%;
      }
      .layout-content {
        width: 67%;
      }
    }
  }
  .layout-transverse {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .layout-dark {
      height: 20%;
    }
    .layout-content {
      height: 67%;
    }
  }
  .layout-columns {
    display: flex;
    justify-content: space-between;
    .layout-dark {
      width: 20%;
    }
    .layout-light {
      width: 20%;
    }
    .layout-content {
      width: 50%;
    }
  }
}

.mb30 {
  margin-bottom: 30px;
}

.mb40 {
  margin-bottom: 40px;
}

.theme-section {
  display: block;
  width: 100%;
  position: relative;
  z-index: 1;
}
</style>
